import asyncio
from common.config.database import async_engine, AsyncSessionLocal, Base
from common.utils.log_util import logger
from sqlalchemy import text  # 导入 text 函数

async def get_db():
    """
    每一个请求处理完毕后会关闭当前连接，不同的请求使用不同的连接

    :return:
    """
    async with AsyncSessionLocal() as current_db:
        yield current_db


async def init_create_table():
    """
    应用启动时初始化数据库连接

    :return:
    """
    logger.info('初始化数据库连接...')
    try:
        async with async_engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
        logger.info('数据库连接成功')
        return True
    except Exception as e:
        logger.error(f'数据库初始化失败，将跳过数据库连接: {str(e)}')
        return False


async def keepalive_db():
    """
    定期发送SELECT 1命令以保持连接活跃
    """
    while True:
        async with AsyncSessionLocal() as session:
            try:
                result = await session.execute(text('SELECT 1'))  # 使用 text 函数声明 SQL 表达式
                result.scalar_one()
                logger.debug('数据库连接保持活跃')
            except Exception as e:
                logger.error(f'数据库心跳检测失败，详细错误信息：{e}')
        await asyncio.sleep(30)  # 每隔30秒发送一次心跳